package com.qf.utils;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.qf.service.impl.PayServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import static io.swagger.models.properties.FloatProperty.FORMAT;

@Component
public class AlipayUtils {

    @Value("${alipay.serverUrl}")
    private String serverUrl;
    @Value("${alipay.APP_ID}")
    private String APP_ID;
    @Value("${alipay.APP_PRIVATE_KEY}")
    private String APP_PRIVATE_KEY;
    @Value("${alipay.FORMAT}")
    private String FORMAT;
    @Value("${alipay.CHARSET}")
    private String CHARSET;
    @Value("${alipay.ALIPAY_PUBLIC_KEY}")
    private String ALIPAY_PUBLIC_KEY;
    @Value("${alipay.SIGN_TYPE}")
    private String SIGN_TYPE;
    @Value("${alipay.returnUrl}")
    private String returnUrl;
    @Value("${alipay.NotifyUrl}")
    private String NotifyUrl;

    private static Logger logger = LoggerFactory.getLogger(PayServiceImpl.class);
    //初始化alipayClient
    //支付请求
    public String alipayClient(String json){
        AlipayClient alipayClient =  new DefaultAlipayClient( serverUrl , APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);  //获得初始化的AlipayClient
        AlipayTradePagePayRequest alipayRequest =  new AlipayTradePagePayRequest(); //创建API对应的request
        alipayRequest.setReturnUrl( returnUrl );
        alipayRequest.setNotifyUrl( NotifyUrl ); //在公共参数中设置回跳和通知地址
        alipayRequest.setBizContent(json); //填充业务参数
        String form= "" ;
        try  {
            form = alipayClient.pageExecute(alipayRequest).getBody();  //调用SDK生成表单
        }  catch  (AlipayApiException e) {
            e.printStackTrace();
        }
        return form;
    }

    //验签操作
    public boolean notifyUrl(HttpServletRequest request){
        //将request请求中的参数转为map
        Map<String, String> map = convertRequestParamsToMap(request);//将异步通知中收到的所有参数都存放到map中
        logger.debug("转换完成的参数为:"+map);
        //2.进行验签操作
        try {
            boolean signVerified = AlipaySignature.rsaCheckV1(map, ALIPAY_PUBLIC_KEY, CHARSET, SIGN_TYPE); //调用SDK验证签名
            return signVerified;
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return false;
        }
    }

    // 将request中的参数转换成Map
    public static Map<String, String> convertRequestParamsToMap(HttpServletRequest request) {
        Map<String, String> retMap = new HashMap<String, String>();

        Set<Map.Entry<String, String[]>> entrySet = request.getParameterMap().entrySet();

        for (Map.Entry<String, String[]> entry : entrySet) {
            String name = entry.getKey();
            String[] values = entry.getValue();
            int valLen = values.length;

            if (valLen == 1) {
                retMap.put(name, values[0]);
            } else if (valLen > 1) {
                StringBuilder sb = new StringBuilder();
                for (String val : values) {
                    sb.append(",").append(val);
                }
                retMap.put(name, sb.toString().substring(1));
            } else {
                retMap.put(name, "");
            }
        }

        return retMap;
    }
}
